package org.wsocket.timer;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.wsocket.WSocket;
import org.wsocket.connector.Connector;

public class TimeOutTimerTask extends TimerTask {
	
	Logger log=Logger.getLogger(this.getClass());
	private ConcurrentHashMap<String, Connector> connectors;
	private ConcurrentHashMap<String, String> c_connectors;
	private ConcurrentHashMap<String, SelectionKey> c_sk;
	
	public TimeOutTimerTask(ConcurrentHashMap<String, Connector> connectors,
			ConcurrentHashMap<String, String> cConnectors,
			ConcurrentHashMap<String, SelectionKey> cSk) {
		super();
		this.connectors = connectors;
		this.c_connectors = cConnectors;
		this.c_sk = cSk;
	}

	@Override
	public void run() {
		if (log.isDebugEnabled()) {
			log.debug("connectors size:" + connectors.size()
					+ "       c_connectors size" + c_connectors.size());
		}
		for(String key : connectors.keySet()){
			if(!c_connectors.containsKey(key)){
				Connector c = connectors.get(key);
				try {
					c.getSocketChannel().close();
					c_sk.remove(key).cancel();
					connectors.remove(key);
					WSocket.getListener().onTimeOut(c.getKey());
				} catch (IOException e) {
					log.error(e);
				}
			}
		}
		c_connectors.clear();
	}

}
